package com.newpage.module_classin.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

import androidx.annotation.Nullable;

import com.wetao.lib_common.AppConfig;
import com.wetao.lib_common.Constants;
import com.wetao.lib_common.utils.LogUtils;
import com.wetao.lib_common.utils.SPUtils;
import com.zhangke.websocket.SocketListener;
import com.zhangke.websocket.WebSocketHandler;
import com.zhangke.websocket.WebSocketManager;
import com.zhangke.websocket.WebSocketSetting;
import com.zhangke.websocket.response.ErrorResponse;

import org.java_websocket.framing.Framedata;

import java.nio.ByteBuffer;

/**
 * author: zhouyh
 * created on: 3/26/21 1:59 PM
 * description: 启动客户端长链接
 */
public class RoomService extends Service {

    private static final String TAG = "RoomService";
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new RoomBinder();
    }


    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }


    @Override
    public void onCreate() {
        super.onCreate();
        initWebSocket();
        WebSocketHandler.getDefault().addListener(socketListener);
    }

    public class RoomBinder extends Binder{
        public RoomService getService(){
            return RoomService.this;
        }
    }


    private void initWebSocket(){
        WebSocketSetting setting = new WebSocketSetting();
        //连接地址，必填，例如 wss://echo.websocket.org
        String URL = AppConfig.SOCKET_URL + "?" + SPUtils.getInstance().getString(Constants.HEAD_XTOKEN);
        LogUtils.e("webSocket url:" + URL);

        setting.setConnectUrl(URL);//必填

        //设置连接超时时间
        setting.setConnectTimeout(15 * 1000);

        //设置心跳间隔时间
        setting.setConnectionLostTimeout(30);

        //设置断开后的重连次数，可以设置的很大，不会有什么性能上的影响
        setting.setReconnectFrequency(10);

        //网络状态发生变化后是否重连，
        //需要调用 WebSocketHandler.registerNetworkChangedReceiver(context) 方法注册网络监听广播
        setting.setReconnectWithNetworkChanged(true);

        //通过 init 方法初始化默认的 WebSocketManager 对象
        WebSocketManager manager = WebSocketHandler.init(setting);
        //启动连接
        manager.start();

        //注意，需要在 AndroidManifest 中配置网络状态获取权限
        //注册网路连接状态变化广播
        WebSocketHandler.registerNetworkChangedReceiver(this);
    }

    public SocketListener socketListener = new SocketListener() {
        @Override
        public void onConnected() {
            if (roomConnectListener!=null){
                roomConnectListener.onConnected();
            }
        }

        @Override
        public void onConnectFailed(Throwable e) {
            if (roomConnectListener!=null){
                roomConnectListener.onConnectFailed(e);
            }
        }

        @Override
        public void onDisconnect() {
            if (roomConnectListener!=null){
                roomConnectListener.onDisconnect();
            }
        }

        @Override
        public void onSendDataSuccess() {
            if (roomConnectListener!=null){
                roomConnectListener.onSendDataSuccess();
            }
        }

        @Override
        public void onSendDataError(ErrorResponse errorResponse) {

        }

        @Override
        public <T> void onMessage(String message, T data) {
            if (roomConnectListener!=null){
                roomConnectListener.onMessage(message);
            }
        }

        @Override
        public <T> void onMessage(ByteBuffer bytes, T data) {

        }

        @Override
        public void onPing(Framedata framedata) {

        }

        @Override
        public void onPong(Framedata framedata) {

        }
    };


    public RoomConnectListener roomConnectListener;
    public interface RoomConnectListener{
         void onConnected();
         void onConnectFailed(Throwable e);
         void onDisconnect();
         void onSendDataSuccess();
         void onSendDataError(ErrorResponse errorResponse);
         void onMessage(String message);
         void onMessage(ByteBuffer bytes);

    }

    public void setRoomConnectListener(RoomConnectListener roomConnectListener) {
        this.roomConnectListener = roomConnectListener;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        WebSocketHandler.getDefault().disConnect();
        WebSocketHandler.unRegisterNetworkReceiver(this);
        WebSocketHandler.release();
    }
}

